package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.alipay.PayResult;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.DecimalEditText;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.popupwindow.PasswordPayPopup;
import com.eightbears.beboy.base.view.popupwindow.PaySelectPopup;
import com.eightbears.beboy.entity.PayInfoEntity;
import com.eightbears.beboy.entity.PayTypeEntity;
import com.eightbears.beboy.entity.SuccessEntity;
import com.eightbears.beboy.entity.WeChatPayEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.login.ForgetActivity;
import com.makeramen.roundedimageview.RoundedImageView;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.socks.library.KLog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAY_ALIPAY;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAY_MYPAY;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PAY_WEIXIN;
import static com.eightbears.beboy.base.util.CommonAPI.WECHAT_APP_ID;
import static com.eightbears.beboy.entity.PayTypeEntity.TYPE_ALIPAY;
import static com.eightbears.beboy.entity.PayTypeEntity.TYPE_MYPAY;
import static com.eightbears.beboy.entity.WaitPaymentEntity.PARAMS_WAIT_PAYMENT;
import static com.eightbears.beboy.ui.user.activity.AddShoppingAddressActivity.EVENT_ADDRESS_SUCCESS;
import static com.eightbears.beboy.ui.user.activity.PaymentActivity.EVENT_WCHAT_PAY_SUCCESS;
import static com.socks.library.KLog.e;

/**
 * Created by Administrator on 2017/9/4.
 */

public class TransferActivity extends BaseActivity {

    public static final String PARAMS_PAY_TRANSFER = "transfer";
    private static final int SDK_PAY_FLAG = 1;
    private String payPlatform = TYPE_MYPAY;
    private String payType = "5";

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_balance_problem)
    TextView tv_balance_problem;
    @BindView(R.id.tv_save_address)
    TextView tv_save_address;
    @BindView(R.id.tv_transfer_text)
    TextView tv_transfer_text;
    @BindView(R.id.iv_head)
    RoundedImageView iv_head;
    @BindView(R.id.sw)
    SwipeBackLayout sw;
    @BindView(R.id.search_clear)
    ImageButton search_clear;
    @BindView(R.id.et_userpay_balance)
    DecimalEditText et_userpay_balance;
    @BindView(R.id.tv_transfer)
    TextView tv_transfer;
    @BindView(R.id.iv_balance)
    ImageView iv_balance;
    @BindView(R.id.tv_way)
    TextView tv_way;
    @BindView(R.id.tv_take_way)
    TextView tv_take_way;


    private InputMethodManager mInputMethodManager;
    private String mBalance;
    private String mUserId;
    private String mCover;
    private String mUsername;
    private PasswordPayPopup mPasswordPayPopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_transfer);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mUsername = getIntent().getStringExtra("nickname");
        mCover = getIntent().getStringExtra("cover");
        mUserId = getIntent().getStringExtra("userId");
        CommonUtils.loadImageView(mContext, mCover, R.mipmap.default_head,
                iv_head);
        tv_title.setText("转账给" + mUsername);
        tv_transfer_text.setText(mUsername);
    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_transfer)
    void transfer() {

        mBalance = et_userpay_balance.getText().toString().trim();
        if (TextUtils.isEmpty(String.valueOf(mBalance)) || mBalance.equals("0")) {
            ShowToast.showShortToast("转账金额不能为空！");
            return;
        }

        if (String.valueOf(mBalance).substring(0, 1).equals(".")) {
            ShowToast.showShortToast("请输入正确的转账金额！");
            return;
        }

        if (String.valueOf(mBalance).substring(0, 1).equals("0") && String.valueOf(mBalance).substring(1, 2).matches("^[0-9]{6,10}$")) {
            ShowToast.showShortToast("请输入正确的转账金额！");
            return;
        }

        if (TextUtils.isEmpty(String.valueOf(mBalance))) {
            ShowToast.showShortToast("转账金额不能为空！");
            return;
        }

        if (Double.parseDouble(mBalance) <= 0) {
            ShowToast.showShortToast("请输入正确的转账金额！");
            return;
        }

        if (payPlatform.equals(TYPE_ALIPAY)) {
            aliPay();
        }

        if (payPlatform.equals(PayTypeEntity.TYPE_WCHAT)) {
            weixinPay();
        }

        if (payPlatform.equals(TYPE_MYPAY)) {
            if (null == mPasswordPayPopup) {
                mPasswordPayPopup = new PasswordPayPopup((Activity) mContext);
            }
            mPasswordPayPopup.setAccountName("向" + mUsername + "转账");
            mPasswordPayPopup.setBalance("￥" + mBalance);
            mPasswordPayPopup.setOnItemClickListener(new PasswordPayPopup.onPasswordPayPopupClickListener() {
                @Override
                public void onItemClick() {
                    startLocalActivity((Activity) mContext, ForgetActivity.class, PARAMS_PAY_TRANSFER, PARAMS_PAY_TRANSFER);
                }
            });
            mPasswordPayPopup.setOnClickSurePayListener(new PasswordPayPopup.OnClickSurePayListener() {
                @Override
                public void onClickItem(TextView mTv_sure, ProgressWheel mProgress_wheel, String mPassword) {
                    myPay(mPassword);
                }
            });
            mPasswordPayPopup.showPopupWindow();
        }
    }

    @OnClick(R.id.tv_take_way)
    void way() {
        PaySelectPopup paySelectPopup = new PaySelectPopup((Activity) mContext);
        paySelectPopup.setOnClickItemListener(new PaySelectPopup.OnClickItemListener() {
            @Override
            public void onClickItem(String payPlatformCall, View v) {
                payPlatform = payPlatformCall;
                initPayInfo();
            }
        });
        paySelectPopup.showPopupWindow();
    }


    @Override
    protected void initEvent() {
        sw.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        search_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_userpay_balance.getText().clear();
                hideSoftKeyboard();
            }
        });

        et_userpay_balance.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    search_clear.setVisibility(View.VISIBLE);
                    if (s.toString().substring(0, 1).equals("0") && s.length() >= 2 && s.toString().substring(1, 2).matches("[0-9]")) {
                        String trans = s.toString().substring(1, s.toString().length());
                        et_userpay_balance.setText(trans);
                        et_userpay_balance.setSelection(trans.length());
                    }
                } else {
                    search_clear.setVisibility(View.INVISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });

//        et_userpay_balance.addTextChangedListener(new TextWatcher() {
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (s.length() > 0) {
//
//                }
//            }
//
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            public void afterTextChanged(Editable s) {
//            }
//        });
    }

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 余额支付
     *
     * @param mPassword
     */

    private void myPay(String mPassword) {
        if (TextUtils.isEmpty(mPassword) || mPassword.length() < 6) {
            ShowToast.showShortToast("请输入支付密码");
            return;
        }
        mPasswordPayPopup.setTextGoneWheelVisiable();
        OkHttpUtils.post().url(URL_PAY_MYPAY)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", payType)
                .addParams("id", mUserId)
                .addParams("transfer_amount", String.valueOf(mBalance))
                .addParams("password", mPassword)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                KLog.e(response);
                mPasswordPayPopup.setTextVisiableWheelGone();
                mPasswordPayPopup.setTextClear();
                SuccessEntity successEntity = GsonUtil.fromJson(response, SuccessEntity.class);
                if (String.valueOf(successEntity.getStatus_code()).equals(CONNECTION_STATUS_SUCCESS)) {
                    startLocalActivity((Activity) mContext, BuyResultActivity.class, PARAMS_PAY_TRANSFER, mBalance);
                    ShowToast.showShortToast(getString(R.string.text_pay_success));
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                mPasswordPayPopup.setTextVisiableWheelGone();
                mPasswordPayPopup.setTextClear();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    /**
     * 微信支付
     */
    private void weixinPay() {
        if (!CommonUtils.isWeixinAvilible(mContext)) {
            ShowToast.showLongToast(getString(R.string.text_install_wchat));
            return;
        }
        OkHttpUtils.post().url(URL_PAY_WEIXIN)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", payType)
                .addParams("id", mUserId)
                .addParams("transfer_amount", String.valueOf(mBalance))
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                KLog.e(response);
                WeChatPayEntity weChatPayEntity = GsonUtil.fromJson(response, WeChatPayEntity.class);
                if (weChatPayEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    weChatPay(weChatPayEntity);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }


    /**
     * 阿里支付
     */
    private void aliPay() {
        OkHttpUtils.post().url(URL_PAY_ALIPAY)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", payType)
                .addParams("id", mUserId)
                .addParams("transfer_amount", String.valueOf(mBalance))
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                PayInfoEntity payInfoEntity = GsonUtil.fromJson(response, PayInfoEntity.class);
                if (payInfoEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    aliPayment(payInfoEntity);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    // 微信支付
    private void weChatPay(WeChatPayEntity weChatPayEntity) {
        IWXAPI api = WXAPIFactory.createWXAPI(mContext, WECHAT_APP_ID);
        api.registerApp(WECHAT_APP_ID);
        WeChatPayEntity.Data data = weChatPayEntity.getData();
        PayReq payReq = new PayReq();
        payReq.appId = data.getApp_id();
        payReq.partnerId = data.getMerchant_id();
        payReq.prepayId = data.getPrepay_id();
        payReq.packageValue = "Sign=WXPay";
        payReq.nonceStr = data.getNonce_str();
        payReq.timeStamp = data.getTimestamp();
        payReq.sign = data.getSign();
        api.sendReq(payReq);
    }

    // 阿里支付
    private void aliPayment(PayInfoEntity payInfoEntity) {
        final String orderInfo = payInfoEntity.getData().getInfo();
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask((Activity) mContext);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                        startLocalActivity((Activity) mContext, BuyResultActivity.class, PARAMS_PAY_TRANSFER, mBalance);
//                        startPayResult();

                        Intent intent = getIntent().putExtra("transfer_amount", mBalance).putExtra("cover", mCover);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "取消支付", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };

    private void initPayInfo() {
        if (payPlatform.equals(TYPE_ALIPAY)) {
            tv_way.setText("支付宝");
            iv_balance.setImageResource(R.mipmap.zfb_icon);
        }
        if (payPlatform.equals(PayTypeEntity.TYPE_WCHAT)) {
            tv_way.setText("微信");
            iv_balance.setImageResource(R.mipmap.wx_icon);
        }
        if (payPlatform.equals(TYPE_MYPAY)) {
            tv_way.setText("余额");
            iv_balance.setImageResource(R.mipmap.icon_balance);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_WCHAT_PAY_SUCCESS:
                startLocalActivity((Activity) mContext, BuyResultActivity.class, PARAMS_PAY_TRANSFER, mBalance);
                Intent intent = getIntent().putExtra("transfer_amount", mBalance).putExtra("cover", mCover);
                setResult(Activity.RESULT_OK, intent);
                finish();
                break;
            case PARAMS_PAY_TRANSFER:
                Intent intent1 = getIntent().putExtra("transfer_amount", mBalance).putExtra("cover", mCover);
                setResult(Activity.RESULT_OK, intent1);
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public PasswordPayPopup getPasswordPayPopup() {
        return mPasswordPayPopup;
    }

}
